package com.example.authservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.authservice.entity.User;
import com.example.authservice.mapper.UserAuthMapper;
import com.example.authservice.service.UserAuthService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserAuthServiceImpl extends ServiceImpl<UserAuthMapper, User> implements UserAuthService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public boolean register(User user) {
        // 校验用户名是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (count(wrapper) > 0) {
            return false; // 用户名已存在
        }

        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return save(user);
    }

    @Override
    public User login(String username, String password) {
        // 使用 QueryWrapper 构建条件查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        // 使用 MyBatis-Plus 的 getOne 方法查询单个用户
        User user = this.getOne(queryWrapper);

        if (user == null) {
            return null; // 用户不存在
        }

        // 校验密码
        if (passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }

        return null; // 密码错误
    }

    @Override
    public IPage<User> pageUsers(Integer current, Integer size, Map<String, Object> params) {
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 动态条件查询
        if (params.containsKey("username") && params.get("username") != null) {
            wrapper.like("username", params.get("username"));
        }
        if (params.containsKey("role") && params.get("role") != null) {
            wrapper.eq("role", params.get("role"));
        }

        return page(page, wrapper);
    }
}
